package com.pig4cloud.pigx.knowledge.support.handler.parse;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Pair;
import com.pig4cloud.pigx.knowledge.config.properties.AiKnowledgeProperties;
import com.pig4cloud.pigx.knowledge.dto.MarkitdownResponseDTO;
import com.pig4cloud.pigx.knowledge.entity.AiDatasetEntity;
import com.pig4cloud.pigx.knowledge.entity.AiDocumentEntity;
import com.pig4cloud.pigx.knowledge.service.AiMarkitdownAssistantService;
import com.pig4cloud.pigx.knowledge.support.constant.FileParserStatusEnums;
import com.pig4cloud.pigx.knowledge.support.constant.FileTypeEnums;
import com.pig4cloud.pigx.knowledge.support.util.ByteArrayMultipartFile;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.List;

/**
 * markitdown 上传文件解析处理程序
 *
 * @author lengleng
 * @date 2024/12/22
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class Office2MdUploadFileParseHandler implements UploadFileParseHandler {

    private final AiKnowledgeProperties aiKnowledgeProperties;

    private final AiMarkitdownAssistantService markitdownAssistantService;

    /**
     * 是否支持指定类型文件
     *
     * @param aiDataset
     * @param documentEntity 文件
     * @return true/false
     */
    @Override
    public boolean supports(AiDatasetEntity aiDataset, AiDocumentEntity documentEntity) {
        String contentType = FileUtil.extName(documentEntity.getFileUrl());
        return aiKnowledgeProperties.getMarkitdown().isEnabled()
                && (FileTypeEnums.DOCX.getType().equals(contentType) || FileTypeEnums.PPTX.getType().equals(contentType) || FileTypeEnums.XLSX.getType().equals(contentType));
    }

    /**
     * file2 字符串
     *
     * @param documentEntity Document 实体
     * @param inputStream    输入流
     * @param extName        ext 名称
     * @return {@link List }<{@link String }>
     */
    @Override
    public Pair<FileParserStatusEnums, String> file2String(AiDocumentEntity documentEntity, InputStream inputStream,
                                                           String extName) {
        try {
            MarkitdownResponseDTO markitdownResponseDTO = markitdownAssistantService
                    .upload(new ByteArrayMultipartFile(documentEntity.getName(), documentEntity.getName(), null, inputStream.readAllBytes()));
            return Pair.of(FileParserStatusEnums.PARSE_SUCCESS, markitdownResponseDTO.getText());
        } catch (Exception e) {
            log.error("文件 {} 解析失败", documentEntity.getName(), e);
            return Pair.of(FileParserStatusEnums.PARSE_FAIL, e.getMessage());
        }
    }

    /**
     * 排序； 数值越大，优先加载
     *
     * @return int
     */
    @Override
    public int getOrder() {
        return 100;
    }
}
